﻿-- =============================================
-- Script Template
-- =============================================
if exists(select * from sysobjects where name='proc_userlookexpertNewshows_2')
drop proc proc_userlookexpertNewshows_2
go
create procedure proc_userlookexpertNewshows_2
@userId int,---用户ID
@expertId int,---专家专题ID
@result int output
as
if exists(select Id from pm_expertNews where Id=1 and ((ColourMoney=0 and Endtime<getdate()) or Endtime<getdate()))
begin
select * from pm_expertNews where Id=@expertId
set @result=1
end
else
begin
if exists(select Id from pm_users where Id=@userId)---判断用户是否存在
begin 
    if exists(select mid from UserLookExpertNewsMsg where userid=@userId and expertid=@expertId)---判断用户是否访问过
    begin
         select Id, CreateTime, UserId, PlayId, PlayQiNo, Extitle, Keyword, Exmiaoshu, Uptime, Endtime, Scheme, ColourMoney, ClickSum, CheckMsg, ExperRemark from pm_expertNews where Id=@expertId
    end
    else
    begin
       declare @usercaibi int,@fanwencaibi int
       set @usercaibi=(select UserColourMoney from pm_users where Id=@userId)
       set @fanwencaibi=(select ColourMoney from pm_expertNews  where Id=@expertId)
       if(@usercaibi<@fanwencaibi)
       begin
           set @result=-2
         return
       end
       else
       begin
          begin tran
	         update  pm_users set UserColourMoney=(UserColourMoney-@fanwencaibi) where Id=@userId
	         update pm_users set UserColourMoney=(UserColourMoney+@fanwencaibi) where Id=(select UserId from pm_expertNews where Id=@expertId)
	         insert into UserLookExpertNewsMsg values(getdate(),@userId,@expertId,@fanwencaibi)
	       if(@@error=0)
	        begin
	          select Id, CreateTime, UserId, PlayId, PlayQiNo, Extitle, Keyword, Exmiaoshu, Uptime, Endtime, Scheme, ColourMoney, ClickSum, CheckMsg, ExperRemark from pm_expertNews where Id=@expertId
	         set @result=1--可以访问
	          commit tran
	        end
	        else
	        begin
	         set @result=0  ---系统繁忙
	          rollback tran
	         end 
       end
    end
end
else
begin
  set @result=-1
end


end

